/*
 * AddMessage.java
 *
 * Created on 31 Maret 2008, 12:36
 */
package usu.perpustakaan.buku.widget.operator;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.RowFilter;
import javax.swing.SwingWorker;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;
import usu.perpustakaan.buku.data.template.Operator;
import usu.perpustakaan.buku.sql.BookLibrarySQL;
import usu.perpustakaan.buku.widget.admin.ManageOperator;
import usu.perpustakaan.buku.widget.template.PanelBlackGreen;
import usu.perpustakaan.buku.widget.template.TableModelOperator;
import usu.perpustakaan.buku.widget.template.TextBoxGlass;
import usu.widget.ButtonGlass;

/**
 *
 * @author  usu
 */
public class AddMessage extends PanelBlackGreen {

    private static final long serialVersionUID = -1;
    private TableModelOperator model;
    private String errorMessage;
    private Connection connectio;
    private ExecutorService executor;

    /** Creates new form BeanForm */
    public AddMessage() {
        executor = Executors.newCachedThreadPool();
        model = new TableModelOperator();
        initComponents();
        table.setModel(model);
        for (int i = 0; i < table.getColumnCount(); i++) {
            table.getColumnModel().getColumn(i).setCellRenderer(new ManageOperator.RenderTable());
        }
        textSearch.getDocument().addDocumentListener(new DocumentListener() {

            @Override
            public void insertUpdate(DocumentEvent e) {
                filterTable(textSearch.getText());
            }

            @Override
            public void removeUpdate(DocumentEvent e) {
                filterTable(textSearch.getText());
            }

            @Override
            public void changedUpdate(DocumentEvent e) {
                filterTable(textSearch.getText());
            }
        });
    }

    /**
     * 
     * @param connection
     */
    public void setConnection(Connection connection) {
        this.connectio = connection;
    }

    public void reset() throws SQLException {
        textMessage.setText("");
        textSearch.setText("");
        textTitle.setText("");
        new LoadOperator().execute();
    }

    /**
     * 
     * @param text
     */
    @SuppressWarnings("unchecked")
    public void filterTable(String text) {
        if (text.trim().equals("")) {
            ((TableRowSorter<TableModel>) table.getRowSorter()).setRowFilter(null);
        } else {
            ((TableRowSorter<TableModel>) table.getRowSorter()).setRowFilter(RowFilter.regexFilter(text));
        }
    }

    /**
     * 
     * @return
     */
    public String getErrorMessage() {
        return errorMessage;
    }

    @Override
    public boolean isValid() {
        if (table.getSelectedRowCount() == 0) {
            errorMessage = "Operator tujuan belum ditentukan";
            return false;
        }
        if (textTitle.getText().trim().equals("")) {
            errorMessage = "Judul pesan masih kosong";
            return false;
        }
        if(textMessage.getText().trim().equals("")){
            errorMessage = "Isi pesan masih kosong";
            return false;
        }
        return true;
    }

    public ButtonGlass getButtonCancel() {
        return buttonCancel;
    }

    public ButtonGlass getButtonSend() {
        return buttonSend;
    }

    public TableModelOperator getModel() {
        return model;
    }

    public JTable getTable() {
        return table;
    }

    public JTextArea getTextMessage() {
        return textMessage;
    }

    public TextBoxGlass getTextSearch() {
        return textSearch;
    }

    public TextBoxGlass getTextTitle() {
        return textTitle;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        usu.perpustakaan.buku.widget.template.ViewPortGlass viewPortGlass1 = new usu.perpustakaan.buku.widget.template.ViewPortGlass();
        usu.perpustakaan.buku.widget.template.ViewPortGlass viewPortGlass2 = new usu.perpustakaan.buku.widget.template.ViewPortGlass();
        table = new javax.swing.JTable();
        textMessage = new javax.swing.JTextArea();
        javax.swing.JLabel jLabel1 = new javax.swing.JLabel();
        javax.swing.JLabel jLabel2 = new javax.swing.JLabel();
        javax.swing.JScrollPane jScrollPane1 = new javax.swing.JScrollPane();
        javax.swing.JLabel jLabel3 = new javax.swing.JLabel();
        javax.swing.JLabel jLabel4 = new javax.swing.JLabel();
        javax.swing.JLabel jLabel5 = new javax.swing.JLabel();
        textSearch = new usu.perpustakaan.buku.widget.template.TextBoxGlass();
        textTitle = new usu.perpustakaan.buku.widget.template.TextBoxGlass();
        javax.swing.JScrollPane jScrollPane2 = new javax.swing.JScrollPane();
        buttonSend = new usu.widget.ButtonGlass();
        buttonCancel = new usu.widget.ButtonGlass();

        viewPortGlass1.setView(table);

        viewPortGlass2.setView(textMessage);

        table.setAutoCreateRowSorter(true);
        table.setForeground(new java.awt.Color(255, 255, 255));
        table.setFillsViewportHeight(true);
        table.setOpaque(false);
        table.setSelectionBackground(new java.awt.Color(51, 255, 52));
        table.setSelectionForeground(new java.awt.Color(0, 0, 0));

        textMessage.setColumns(20);
        textMessage.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        textMessage.setForeground(new java.awt.Color(255, 255, 255));
        textMessage.setLineWrap(true);
        textMessage.setRows(5);
        textMessage.setWrapStyleWord(true);
        textMessage.setBorder(javax.swing.BorderFactory.createEmptyBorder(10, 10, 10, 10));
        textMessage.setFocusAccelerator('I');
        textMessage.setOpaque(false);

        setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0), 3));
        setMinimumSize(new java.awt.Dimension(642, 499));

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 24));
        jLabel1.setForeground(new java.awt.Color(255, 255, 255));
        jLabel1.setText("Kirim Pesan");

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel2.setForeground(new java.awt.Color(255, 255, 255));
        jLabel2.setText("Tujuan");

        jScrollPane1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        jScrollPane1.setOpaque(false);
        jScrollPane1.setViewport(viewPortGlass1);

        jLabel3.setDisplayedMnemonic('C');
        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel3.setForeground(new java.awt.Color(255, 255, 255));
        jLabel3.setText("Cari (case sensitive)");

        jLabel4.setDisplayedMnemonic('J');
        jLabel4.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel4.setForeground(new java.awt.Color(255, 255, 255));
        jLabel4.setText("Judul Pesan");

        jLabel5.setDisplayedMnemonic('I');
        jLabel5.setFont(new java.awt.Font("Tahoma", 1, 11));
        jLabel5.setForeground(new java.awt.Color(255, 255, 255));
        jLabel5.setText("Isi Pesan");

        textSearch.setForeground(new java.awt.Color(255, 255, 255));
        textSearch.setHorizontalAlignment(javax.swing.JTextField.LEFT);
        textSearch.setFocusAccelerator('C');
        textSearch.setFont(new java.awt.Font("Tahoma", 1, 11));

        textTitle.setForeground(new java.awt.Color(255, 255, 255));
        textTitle.setHorizontalAlignment(javax.swing.JTextField.LEFT);
        textTitle.setFocusAccelerator('J');
        textTitle.setFont(new java.awt.Font("Tahoma", 1, 11));

        jScrollPane2.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        jScrollPane2.setOpaque(false);
        jScrollPane2.setViewport(viewPortGlass2);

        buttonSend.setMnemonic('K');
        buttonSend.setText("Kirim");
        buttonSend.setRoundRect(true);

        buttonCancel.setMnemonic('B');
        buttonCancel.setText("Batal");
        buttonCancel.setRoundRect(true);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 616, Short.MAX_VALUE)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 616, Short.MAX_VALUE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel5, javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.LEADING))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(textTitle, javax.swing.GroupLayout.DEFAULT_SIZE, 497, Short.MAX_VALUE)
                            .addComponent(textSearch, javax.swing.GroupLayout.DEFAULT_SIZE, 497, Short.MAX_VALUE)))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(buttonCancel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(buttonSend, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(textSearch, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(textTitle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 160, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(buttonSend, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(buttonCancel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    usu.widget.ButtonGlass buttonCancel;
    usu.widget.ButtonGlass buttonSend;
    javax.swing.JTable table;
    javax.swing.JTextArea textMessage;
    usu.perpustakaan.buku.widget.template.TextBoxGlass textSearch;
    usu.perpustakaan.buku.widget.template.TextBoxGlass textTitle;
    // End of variables declaration//GEN-END:variables

    /**
     * 
     */
    public class LoadOperator extends SwingWorker<List<Operator>, String> {

        private ResultSet result;

        /**
         * 
         * @throws java.sql.SQLException
         */
        public LoadOperator() throws SQLException {
            super();
            result = BookLibrarySQL.getResultOperator(connectio);

            model.removeAllElements();
        }

        @Override
        protected List<Operator> doInBackground() throws Exception {
            ArrayList<Operator> array = new ArrayList<Operator>();
            while (result.next()) {
                array.add(BookLibrarySQL.getOperatorFromResultSet(result));
            }
            return array;
        }

        @Override
        protected void done() {
            executor.execute(new Runnable() {

                @Override
                public void run() {
                    try {
                        model.add(get());
                    } catch (InterruptedException ex) {
                        Logger.getLogger(AddMessage.class.getName()).log(Level.SEVERE, null, ex);
                    } catch (ExecutionException ex) {
                        Logger.getLogger(AddMessage.class.getName()).log(Level.SEVERE, null, ex);
                    } finally {
                        try {
                            result.close();
                        } catch (SQLException ex) {
                            Logger.getLogger(AddMessage.class.getName()).log(Level.SEVERE, null, ex);
                        }
                    }
                }
            });
        }
    }
}
